package com.baizhi.service.impl;

import com.baizhi.dao.UserDao;
import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

public class UserServiceImpl implements UserService {
    private SqlSession session = null;
    private UserDao dao = null;
    @Override
    public User selectByName(String name) {
        User user = null;
        try {
            session = MybatisUtil.openSession();
            dao = session.getMapper(UserDao.class);
            user = dao.selectByName(name);
            session.commit();
        } catch (Exception e) {
            if(session!=null){
                session.rollback();
            }
            throw new RuntimeException(e);
        }finally{
            if(session!=null){
                MybatisUtil.close(session);
            }
        }
        return user;
    }

    @Override
    public void insert(User u) {
        try {
            session = MybatisUtil.openSession();
            dao = session.getMapper(UserDao.class);
            dao.insert(u);
            session.commit();
        } catch (Exception e) {
            if(session!=null){
                session.rollback();
            }
            throw new RuntimeException(e);
        }finally{
            if(session!=null){
                MybatisUtil.close(session);
            }
        }
    }
}
